﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AutoSetParticleOrder : MonoBehaviour
{

    private ParticleSystemRenderer[] _particleSystemRenderer;

    // Start is called before the first frame update
    void Start()
    {
       SetParticleOrder();
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    private void OnEnable()
    {
        // SetParticleOrder();
    }

    public void SetParticleOrder()
    {
        Canvas canvas = FindCanvas();
        if (canvas == null)
        {
            return;
        }

        int Dvalue = 0;
        _particleSystemRenderer = GetComponentsInChildren<ParticleSystemRenderer>();
        foreach(ParticleSystemRenderer renderer in _particleSystemRenderer)
        {
            int order = renderer.sortingOrder;
            int _Dvalue = Mathf.FloorToInt(order / 10);
            if (_Dvalue > Dvalue)
                Dvalue = _Dvalue;
        }

        int canvasOrder = canvas.sortingOrder;
        foreach (ParticleSystemRenderer renderer in _particleSystemRenderer)
        {
            int order = renderer.sortingOrder;
            renderer.sortingOrder = order - Dvalue*10 + canvasOrder;
        }
    }

    public Canvas FindCanvas()
    {
        Canvas canvas = GetComponentInParent<Canvas>();
        if (canvas != null)
        {
            return canvas;
        }

        return null;
    }

}
